package com.haiertvbic.timeline;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.haiertvbic.timeline.bean.ImageInfo;
import com.haiertvbic.timeline.constants.TimeLineConstants;
import com.haiertvbic.timeline.constants.WeiBoConstants;
import com.haiertvbic.timeline.constants.WeiXinConstants;
import com.haiertvbic.timeline.task.TimeLineTask;
import com.haiertvbic.timeline.util.TimeLineUtil;
import com.haiertvbic.timeline.weibo.AccessTokenKeeper;
import com.haiertvbic.timeline.weibo.WeiBoHelper;
import com.haiertvbic.tvnow.R;
import com.haiertvbic.tvnow.TVNOWMainActivity;
import com.haiertvbic.tvnow.network.EPGWeb;
import com.haiertvbic.tvnow.pop.PipPop;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.widget.PipCache;
import com.sina.weibo.sdk.WeiboSDK;
import com.sina.weibo.sdk.api.IWeiboAPI;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXImageObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.sso.SsoHandler;

public class MainActivity extends Activity {
	private ListView mTimeLineList;
	private LinearLayout mProgressLayout;
	private AlertDialog mShareSelectDialog;
	private static HashMap<String, ImageInfo> mImageIdMap = new HashMap<String, ImageInfo>();
	private static LinkedList<ImageInfo> mLinkedList = new LinkedList<ImageInfo>();
	private Weibo mWeibo;
	public static Oauth2AccessToken mAccessToken;
	private SsoHandler mSsoHandler;
	private IWeiboAPI mWeiboAPI;
	public static boolean mFlushFlag = false;
	private IWXAPI mIwxapi;
	private static final int THUMB_SIZE = 50;
	private static final String TAG = "MainActivity";
	private boolean mIsFirst = true;

	private String channelId;
	private String picID;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case TimeLineConstants.WEIBO_SHARE_SUCCESS:
				Toast.makeText(MainActivity.this, "微博分享成功", Toast.LENGTH_SHORT)
						.show();
				mShareSelectDialog.dismiss();
				break;
			case TimeLineConstants.WEIBO_SHARE_FAIL:
				Toast.makeText(MainActivity.this, "微博分享失败", Toast.LENGTH_SHORT)
						.show();
				break;
			case TimeLineConstants.PROGRESS_LAYOUT_SHOW:
				mProgressLayout.setVisibility(View.VISIBLE);
				break;
			case TimeLineConstants.PROGRESS_LAYOUT_DISMISS:
				mProgressLayout.setVisibility(View.GONE);
				switch (msg.arg1) {
				case TimeLineConstants.DATA_UPDATE_SUCCESS:
					Toast.makeText(MainActivity.this, "数据获取成功",
							Toast.LENGTH_SHORT).show();
					mProgressLayout.setVisibility(View.VISIBLE);
					filmTop.setVisibility(View.VISIBLE);
					mProgressLayout.setVisibility(View.GONE);
					break;
				case TimeLineConstants.DATA_UPDATE_FAIL:
					Toast.makeText(MainActivity.this, "数据获取失败",
							Toast.LENGTH_SHORT).show();
					break;
				default:
					break;
				}
			}
		}
	};
	private ImageView filmTop;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initView();
		getChannelData();
		initWeiBo();
		initWeiXin();
		registerListener();
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// 删除分享图片时缓存在files文件夹下的图片文件
				deleteFilesFromDataFile();
			}
		}).start();
	}

	private void initWeiXin() {
		// TODO Auto-generated method stub
		mIwxapi = WXAPIFactory.createWXAPI(this, WeiXinConstants.APP_ID, true);
		mIwxapi.registerApp(WeiXinConstants.APP_ID);
	}

	private void deleteFilesFromDataFile() {
		// TODO Auto-generated method stub
		String filePath = MainActivity.this.getApplicationContext()
				.getFilesDir().getAbsolutePath();
		TimeLineUtil.deleteAllFile(filePath);
	}

	private void registerListener() {
		// TODO Auto-generated method stub
		mTimeLineList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {
				// TODO Auto-generated method stub
				LayoutInflater inflater = getLayoutInflater();
				View view = inflater.inflate(R.layout.share_dialog,
						(ViewGroup) findViewById(R.id.share_dialog));
				Button share_sina = (Button) view.findViewById(R.id.share_sina);
				Button share_weixin = (Button) view
						.findViewById(R.id.share_weixin);
				share_sina.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// Toast.makeText(MainActivity.this, "分享到微博",
						// Toast.LENGTH_SHORT).show();
						if (MainActivity.mAccessToken.isSessionValid()) {
							// Toast.makeText(MainActivity.this,
							// "token 有效 直接分享",
							// Toast.LENGTH_SHORT).show();
							ImageInfo info = mLinkedList.get(arg2);

							// 缓存图片到本地
							TimeLineUtil.saveBitmapToFile(MainActivity.this,
									info.getImageBitmap(), info.getImageId());
							SLog.i("soul", MainActivity.this.getFilesDir()
									.getAbsolutePath());
							String path = MainActivity.this.getFilesDir()
									.getAbsolutePath()
									+ File.separator
									+ info.getImageId() + ".png";
							File file = new File(path);
							if (!file.exists()) {
								Toast.makeText(MainActivity.this,
										"文件不存在 " + path, Toast.LENGTH_LONG)
										.show();
								return;
							}
							try {
								WeiBoHelper.upload(MainActivity.this, mHandler,
										mWeibo, WeiBoConstants.APP_KEY, path,
										"来自tvnow的图片", "", "");
							} catch (WeiboException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} else {
							mSsoHandler = new SsoHandler(MainActivity.this,
									mWeibo);
							mSsoHandler.authorize(new AuthDialogListener(),
									null);
						}
					}
				});
				share_weixin.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// Toast.makeText(MainActivity.this, "分享到微信",
						// Toast.LENGTH_SHORT).show();
						ImageInfo info = mLinkedList.get(arg2);

						// 缓存图片到本地
						TimeLineUtil.saveBitmapToFile(MainActivity.this,
								info.getImageBitmap(), info.getImageId());
						SLog.i("soul", MainActivity.this.getFilesDir()
								.getAbsolutePath());
						String path = MainActivity.this.getFilesDir()
								.getAbsolutePath()
								+ File.separator
								+ info.getImageId() + ".png";
						File file = new File(path);
						if (!file.exists()) {
							Toast.makeText(MainActivity.this, "文件不存在 " + path,
									Toast.LENGTH_LONG).show();
							SLog.d("soul", "文件不存在");
							return;
						} else {
							SLog.d("soul", "文件存在");
						}

						WXImageObject imgObj = new WXImageObject();
						imgObj.setImagePath(path);

						WXMediaMessage msg = new WXMediaMessage();
						msg.mediaObject = imgObj;

						Bitmap bmp = BitmapFactory.decodeFile(path);
						Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp,
								THUMB_SIZE, THUMB_SIZE, true);
						bmp.recycle();
						msg.thumbData = TimeLineUtil.bmpToByteArray(thumbBmp,
								true);

						SendMessageToWX.Req req = new SendMessageToWX.Req();
						req.transaction = buildTransaction("img");
						req.message = msg;
						req.scene = true ? SendMessageToWX.Req.WXSceneTimeline
								: SendMessageToWX.Req.WXSceneSession;
						mIwxapi.sendReq(req);
					}
				});
				boolean weixinStatus = appIsInstalled("com.tencent.mm");
				if (!weixinStatus) {
					share_weixin.setVisibility(View.GONE);
				}
				int[] arrayOfInt = new int[2];
				arg1.getLocationInWindow(arrayOfInt);
				mShareSelectDialog = new AlertDialog.Builder(arg1.getContext(),
						R.style.dialog).setView(view).create();
				Window win = mShareSelectDialog.getWindow();
				LayoutParams params = new LayoutParams();
				float pictureHeight = getResources().getDimension(
						R.dimen.picture_height);
				float pictureWidth = getResources().getDimension(
						R.dimen.picture_width);
				SLog.d(TAG, "pictureHeight===" + pictureHeight);
				SLog.d(TAG, "pictureWidth=======" + pictureWidth);
				// 2.2;2,值越大,越向左
				params.x = (int) (arrayOfInt[0] - pictureWidth * 2.0);// 设置x坐标
				// params.x = 0,值越小,越靠下;
				params.y = (int) (arrayOfInt[1] - pictureHeight * 2.16);// 设置y坐标
				SLog.d(TAG, "arrayOfInt[0]===" + arrayOfInt[0]);
				SLog.d(TAG, "arrayOfInt[1]=======" + arrayOfInt[1]);
				win.setAttributes(params);
				mShareSelectDialog.show();

			}
		});
	}

	private void initWeiBo() {
		// TODO Auto-generated method stub
		mWeibo = Weibo.getInstance(WeiBoConstants.APP_KEY,
				WeiBoConstants.REDIRECT_URL, WeiBoConstants.SCOPE);
		MainActivity.mAccessToken = AccessTokenKeeper.readAccessToken(this);
		mWeiboAPI = WeiboSDK.createWeiboAPI(this, WeiBoConstants.APP_KEY);
		mWeiboAPI.registerApp();
	}

	private void initView() {
		// TODO Auto-generated method stub

		mTimeLineList = (ListView) this.findViewById(R.id.time_line);
		mProgressLayout = (LinearLayout) this
				.findViewById(R.id.progress_layout);
		filmTop = (ImageView) this.findViewById(R.id.film_top);
		RelativeLayout anim = (RelativeLayout) this
				.findViewById(R.id.timeline_anim);
		Animation rightAnimation = AnimationUtils.loadAnimation(this,
				R.anim.slide_in_up);
		rightAnimation.setStartOffset(100);
		anim.startAnimation(rightAnimation);
		mImageIdMap.clear();
		mLinkedList.clear();
	}

	private void getChannelData() {
		Intent intent = getIntent();
		channelId = intent.getIntExtra("CHA_ID", -1) + "";
		picID = "000";
		if (PipCache.getPipMap().get(channelId) != null) {
			picID = PipCache.getPipMap().get(channelId).getImageId();
			// ImageInfo image = new ImageInfo();
			// image.setImageId(picID);
			// image.setImageBitmap(PipCache.getPipMap().get(channelId).getBm());
			// image.setImageUrl(PipCache.getPipMap().get(channelId).getPipUrl());
			// mLinkedList.addFirst(image);
		}
		SLog.d(TAG, "第一屏传来的频道id是：" + channelId + "---图片id" + picID);
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (mIsFirst) {
			mIsFirst = false;
			TimeLineTask timeLineTask = new TimeLineTask(this, mHandler,
					mTimeLineList, mLinkedList, mImageIdMap, channelId, picID,
					"");
			timeLineTask.execute();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		this.finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_UP:
			if (mTimeLineList != null
					&& mTimeLineList.getSelectedItemPosition() == 0
					&& mFlushFlag) {
				mFlushFlag = false;
				int count = mLinkedList.size() - 1;
				for (int i = 0; i < 5; i++) {
					SLog.i(TAG, "脚标为==" + i + "的图片id为=="
							+ mLinkedList.get(i).getImageId());
				}
				TimeLineTask timeLineTask = new TimeLineTask(this, mHandler,
						mTimeLineList, mLinkedList, mImageIdMap, channelId,
						mLinkedList.get(0).getImageId(), "right");
				timeLineTask.execute();
				mHandler.sendEmptyMessage(TimeLineConstants.PROGRESS_LAYOUT_SHOW);
				SLog.d(TAG, "0的图片id为==" + mLinkedList.get(0).getImageId());
			}
			break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			mImageIdMap.clear();
			mLinkedList.clear();
			Intent intent = new Intent();
			intent.setClass(this, TVNOWMainActivity.class);
			startActivity(intent);
			TVNOWMainActivity.pip = new PipPop(this, channelId);
			TVNOWMainActivity.pip.showPop();

			break;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	class AuthDialogListener implements WeiboAuthListener {

		@Override
		public void onComplete(Bundle values) {

			String code = values.getString("code");
			if (code != null) {
				Toast.makeText(MainActivity.this, "认证code成功",
						Toast.LENGTH_SHORT).show();
				return;
			}
			String token = values.getString("access_token");
			SLog.i("soul", "token = " + token);
			final String uid = values.getString("uid");
			// 起线程加用户统计pbs
			SLog.i("soul", "uid = " + uid);

			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					String userInfor = WeiBoHelper.getUserInfo(
							MainActivity.this, Long.valueOf(uid));
					SLog.d(TAG, "用户信息==" + userInfor);
					EPGWeb.uploadXinLangInfor(getApplicationContext(),
							userInfor);
				}
			}).start();
			String expires_in = values.getString("expires_in");
			MainActivity.mAccessToken = new Oauth2AccessToken(token, expires_in);
			if (MainActivity.mAccessToken.isSessionValid()) {
				String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
						.format(new java.util.Date(MainActivity.mAccessToken
								.getExpiresTime()));
				SLog.i("soul", "认证成功: \r\n access_token: " + token + "\r\n"
						+ "expires_in: " + expires_in + "\r\n有效期：" + date);

				AccessTokenKeeper.keepAccessToken(MainActivity.this,
						mAccessToken);
				Toast.makeText(MainActivity.this, "认证成功", Toast.LENGTH_SHORT)
						.show();
			}
		}

		@Override
		public void onError(WeiboDialogError e) {
			Toast.makeText(getApplicationContext(),
					"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(getApplicationContext(), "Auth cancel",
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(getApplicationContext(),
					"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// sso 授权回调
		if (mSsoHandler != null) {
			mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	/**
	 * 用户统计
	 * 
	 * @param uid
	 */
	private void getUserMessage(String uid) {
		WeiBoHelper.getUserInfo(MainActivity.this, Long.valueOf(uid));
	}

	private boolean appIsInstalled(String packageName) {
		List<PackageInfo> list = getPackageManager().getInstalledPackages(
				PackageManager.GET_ACTIVITIES);
		for (PackageInfo packageInfo : list) {
			if (packageInfo.packageName.equals(packageName)) {
				return true;
			}
		}
		return false;
	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}
}
